<template>
	<view class="p-5">
		<view class="">
			<u-form :model="loginForm" :rules="rules" ref="form" :errorType="errorType">
				<u-form-item prop="username">
					<u-input placeholder="账号" prefixIcon="account" prefixIconStyle="font-size: 22px;color: #909399"
						clearable class="bg-white" v-model="loginForm.username"></u-input>
				</u-form-item>
				<u-form-item prop="password">
					<u-input placeholder="密码" prefixIcon="lock" prefixIconStyle="font-size: 22px;color: #909399"
						clearable type="password" class="bg-white" v-model="loginForm.password"></u-input>
				</u-form-item>
				<u-form-item prop="code">
					<u-input placeholder="验证码" prefixIcon="integral" prefixIconStyle="font-size: 22px;color: #909399"
						clearable class="bg-white" v-model="loginForm.code"></u-input>
					<u-image :src="codeUrl" height="40px" width="120px" mode="aspectFit" @click="getCode"></u-image>
				</u-form-item>
			</u-form>



			<view class="mt-3 flex">
				
			</view>
			<view class="mt-3">
				<u-button type="primary" @click="onSubmit">登录</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request.js'
	export default {
		data() {
			return {
				codeUrl: '',
				loginForm: {
					username: 'admin',
					password: 'admin123',
					rememberMe: false,
					code: '',
					uuid: '',
					platform: 2
				},
				rules: {
					username: {
						type: 'string',
						required: true,
						message: '用户名不能为空',
						trigger: ['blur', 'change']
					},
					password: {
						type: 'string',
						required: true,
						message: '密码不能为空',
						trigger: ['blur', 'change']
					},
					code: {
						type: 'string',
						required: true,
						len: 4,
						message: '请填写4位验证码',
						trigger: ['blur']
					},
				},
				errorType: 'toast',
			}
		},
		onLoad() {
			this.getCode()
		},
		methods: {
			onSubmit() {
				this.$refs.form.validate().then(res => {
					console.log(this.loginForm)
					request('login', {
						method: 'post',
						data: this.loginForm,
						withoutToken: true
					}).then(res => {
						const {token} = res
						this.$store.commit('setToken', token)
						request('getInfo').then(res => {
							const {user} = res
							this.$store.commit('setUser', user)
							uni.switchTab({
								url:'/pages/index/index'
							})
						})
					})
				}).catch(errors => {
					console.log(errors)
					const [err] = errors
					
					uni.$u.toast(err.message)
				})
			},
			getCode() {
				request('captchaImage', {
					withoutToken: true
				}).then(res => {
					console.log(res)
					const {
						img,
						uuid
					} = res
					this.codeUrl = `data:image/gif;base64,${img}`
					this.loginForm.uuid = uuid
				})
			},
		},
	}
</script>

<style>
</style>
